<template>

  <el-select v-model="key" class="filter-item" clearable :placeholder="placeholder" @clear="clearOption">
    <el-option ref="op" :value="key" :label="label" :style="'height: '+treeHeight+'px;width:240px;padding: 0;'">
      <el-tree
        ref="tree"
        :data="nodes"
        node-key="id"
        class="permission-tree"
        style="height: 100%"
        default-expand-all
        :check-strictly="true"
        show-checkbox
        @check="checkGroupNode"
      >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                        <i :class="data.icon"></i>{{ data[options.label] }}&nbsp;
                    </span>
                </span>
      </el-tree>
    </el-option>
  </el-select>

</template>

<script>

  export default {
    name: 'TreeSelect',
    props: {
      nodes: undefined,
      placeholder: undefined,
      value: 0,
      ops: undefined,
      hasRoot: false
    },
    data() {
      return {
        map: new Map(),
        key: this.value,
        options: Object.assign({
          key: 'key',
          label: 'name'
        }, this.ops)
      }
    },
    computed: {
      treeHeight() {
        const len = this.parseTree(0, this.$props.nodes)
        this.key = this.value
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys([this.key]);
        })
        return len * 26
      },
      label: {
        get(){
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys([this.key]);
          })
          return this.map.get(this.key)
        },
        set(newValue){
          return newValue
        }
      }
    },
    mounted() {

    },
    methods: {
      checkGroupNode: function (a, b) {
        if (b.checkedKeys.length > 0) {
          this.$refs.tree.setCheckedKeys([a[this.options.key]]);
          this.key = a[this.options.key]
          this.label = a[this.options.label]
          //将v-model绑定向父节点传递,更新父节点的v-model
          this.$emit('input',this.key)
        }
      },
      parseTree(i, tree){
        tree.forEach(item => {
          i++
          this.map.set(item[this.options.key],item[this.options.label])
          if (item.children) {
            i = this.parseTree(i, item.children)
          }
        })
        return i
      },
      clearOption(){
        this.$emit('input',undefined)
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
